require 'qiniu'

Qiniu.establish_connection! access_key: ENV['QINIU_ACCESS_KEY'], secret_key: ENV['QINIU_SECRET_KEY']

module AnAnCommon
  module Qiniu
    # 上传文件到七牛
    def self.upload_file(src_file_path, qn_key, qn_bucket: '')
      qn_bucket  = ::AnAnCommon::QINIU_BUCKET if qn_bucket.blank?
      put_policy = ::Qiniu::Auth::PutPolicy.new(qn_bucket, qn_key)

      # 生成上传 Token
      uptoken = ::Qiniu::Auth.generate_uptoken(put_policy)

      # 调用 upload_with_token_2 方法上传
      ::Qiniu::Storage.upload_with_token_2(uptoken, src_file_path, qn_key, nil, bucket: qn_bucket)
    end

    # 生成七牛完整 url
    def self.url(qn_key, style=nil)
      return if qn_key.nil?
      result = URI.join(::AnAnCommon::QINIU_BUCKET_DOMAIN, qn_key).to_s
      if style
        if Rails.env.production?
          result = "#{result}-#{style}"
        else
          result = "#{result}?#{style}"
        end
      end
      result
    end

    # 生成七牛完整 url
    def self.generate_url(qn_key, options={})
      return if qn_key.nil?
      result = URI.join(::AnAnCommon::QINIU_BUCKET_DOMAIN, qn_key).to_s
      style = options[:style]
      if style
        if Rails.env.production?
          result = "#{result}-#{style}"
        else
          result = "#{result}?#{style}"
        end
      end
      result.sub!(/^https?\:/, '') if options[:protocol] == :relative
      result
    end

    # 生成文件的key
    def self.generate_uploader_key(namespace, file_extension, file_prefix: '')
      [namespace, "#{file_prefix}#{SecureRandom.base58(32)}.#{file_extension}"].compact.join('/')
    end
  end
end
